﻿//
// (C) Copyright 2009 Irantha Suwandarathna (iranthas@hotmail.com)
// All rights reserved.
//

/* Copyright (c) 2001-2008, The HSQL Development Group
 * All rights reserved.
 *
 * Redistribution and use _in source and binary forms, with or without
 * modification, are permitted provided that the following conditions are met:
 *
 * Redistributions of source code must retain the above copyright notice, this
 * list of conditions and the following disclaimer.
 *
 * Redistributions _in binary form must reproduce the above copyright notice,
 * this list of conditions and the following disclaimer _in the documentation
 * and/or other materials provided with the distribution.
 *
 * Neither the name of the HSQL Development Group nor the names of its
 * contributors may be used to endorse or promote products derived from this
 * software without specific prior written permission.
 *
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
 * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
 * ARE DISCLAIMED. IN NO EVENT SHALL HSQL DEVELOPMENT GROUP, HSQLDB.ORG,
 * OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
 * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
 * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
 * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
 * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
 * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 */

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
using EffiProz.Core.Errors;
using EffiProz.Core.Lib;
using EffiProz.Core;


namespace EffiProz.Core.DataTypes
{
    public class BinaryData : BlobData
    {
        public static BinaryData singleBitZero =
        new BinaryData(new byte[] { 0 }, 1);
        public static BinaryData singleBitOne =
            new BinaryData(new byte[] { 0x01 }, 1);
        public static BinaryData zeroLengthBinary =
            new BinaryData(new byte[0], false);
        long id;
        public byte[] data;
        private bool _isBits;
        private long _bitLength;

        public static BinaryData getBitData(byte[] data, long bitLength)
        {

            if (bitLength == 1)
            {
                return data[0] == 0 ? singleBitZero
                                    : singleBitOne;
            }

            return new BinaryData(data, bitLength);
        }

        /**
         * This constructor is used inside the engine when an already serialized
         * byte[] is read from a file (.log, .script, .data or text table source).
         * In this case clone is false.
         *
         * When a byte[] is submitted as a parameter of PreparedStatement then
         * clone is true.
         */
        public BinaryData(byte[] data, bool clone)
        {

            if (clone)
            {
                data = (byte[])ArrayUtil.duplicateArray(data);
            }

            this.data = data;
            this._bitLength = data.Length * 8;
        }

        public BinaryData(SessionInterface session, BlobData b1, BlobData b2)
        {

            long length = (b1.length(session) + b2.length(session));

            if (length > int.MaxValue)
            {
                throw Error.error(ErrorCode.X_22001);
            }

            data = new byte[(int)length];

            Array.Copy(b1.getBytes(), 0, data, 0, (int)b1.length(session));
            Array.Copy(b2.getBytes(), 0, data, (int)b1.length(session),
                             (int)b2.length(session));

            this._bitLength = (b1.length(session) + b2.length(session)) * 8;
        }

        public BinaryData(byte[] data, long bitLength)
        {

            this.data = data;
            this._bitLength = bitLength;
            this._isBits = true;
        }

        public BinaryData(long length, Stream stream)
        {

            data = new byte[(int)length];
            _bitLength = data.Length * 8;

            try
            {
                stream.Read(data, 0, (int)length);
            }
            catch (IOException e)
            {
                throw Error.error(ErrorCode.GENERAL_IO_ERROR, e);
            }
        }

        public byte[] getBytes()
        {
            return data;
        }

        public long length(SessionInterface session)
        {
            return data.Length;
        }

        public long bitLength(SessionInterface session)
        {
            return _bitLength;
        }

        public bool isBits()
        {
            return _isBits;
        }

        public byte[] getBytes(SessionInterface session, long pos, int length)
        {

            if (!isInLimits(data.Length, pos, length))
            {
                throw new IndexOutOfRangeException();
            }

            byte[] bytes = new byte[length];

            Array.Copy(data, (int)pos, bytes, 0, length);

            return bytes;
        }

        public BlobData getBlob(SessionInterface session, long pos, long length)
        {
            throw Error.runtimeError(ErrorCode.U_S0500, "BinaryData");
        }

        public Stream getBinaryStream(SessionInterface session)
        {
            return new BlobInputStream(session, this, 0L, length(session));
        }

        public Stream getBinaryStream(SessionInterface session, long pos,
                                           long len)
        {

            if (!isInLimits(data.Length, pos, len))
            {
                throw new IndexOutOfRangeException();
            }

            return new BlobInputStream(session, this, pos, length(session));
        }

        public int setBytes(SessionInterface session, long pos, byte[] bytes,
                            int offset, int length)
        {

            if (!isInLimits(data.Length, pos, 0))
            {
                throw new IndexOutOfRangeException();
            }

            if (!isInLimits(data.Length, pos, length))
            {
                data = (byte[])ArrayUtil.resizeArray(data, (int)pos + length);
            }

            Array.Copy(bytes, offset, data, (int)pos, length);

            _bitLength = data.Length * 8;

            return length;
        }

        public int setBytes(SessionInterface session, long pos, byte[] bytes)
        {

            setBytes(session, pos, bytes, 0, bytes.Length);

            return bytes.Length;
        }

        public long setBinaryStream(SessionInterface session, long pos,
                                    Stream _in)
        {
            return 0;
        }

        public Stream setBinaryStream(SessionInterface session, long pos)
        {
            return null;
        }

        public void truncate(SessionInterface session, long len)
        {

            if (data.Length > len)
            {
                data = (byte[])ArrayUtil.resizeArray(data, (int)len);
                _bitLength = data.Length * 8;
            }
        }

        public BlobData duplicate(SessionInterface session)
        {
            return new BinaryData(data, true);
        }

        public long position(SessionInterface session, byte[] pattern,
                             long start)
        {

            if (pattern.Length > data.Length)
            {
                return -1;
            }

            if (start >= data.Length)
            {
                return -1;
            }

            return ArrayUtil.find(data, (int)start, data.Length, pattern);
        }

        public long position(SessionInterface session, BlobData pattern,
                             long start)
        {

            if (pattern.length(session) > data.Length)
            {
                return -1;
            }

            byte[] bytes = pattern.getBytes();

            return position(session, bytes, start);
        }

        public long nonZeroLength(SessionInterface session)
        {

            // temp
            return data.Length;
        }

        public long getId()
        {
            return id;
        }

        public void setId(long id)
        {
            this.id = id;
        }

        public int getStreamBlockSize()
        {
            return 512 * 1024;
        }

        public bool isClosed()
        {
            return false;
        }

        public void free() { }

        public void setSession(SessionInterface session) { }

        //---
        static bool isInLimits(long fullLength, long pos, long len)
        {
            return pos >= 0 && len >= 0 && pos + len <= fullLength;
        }

        public bool isBinary()
        {
            return true;
        }
    }
}
